﻿using EMS.system.Entityies.WarehouseManagement.WarehouseSettingsModel;
using EMS.system.IEntityAppService.WarehouseManagement.WarehouseSetup;
using EMS.system.IEntityAppService.WarehouseManagement.WarehouseSetup.WarehouseSetupDTO;
using System;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace EMS.system.EntityAppService.WarehouseManagement.WarehouseSetup
{
    public class WarehouseSetupAppService : systemAppService, IWarehouseSetupAppService
    {
        private readonly IRepository<WarehouseSettings, int> _repository;

        public WarehouseSetupAppService(IRepository<WarehouseSettings, int> repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 新增仓库
        /// </summary>
        public async Task<int> AddWarehouseSetup(WarehouseSetupInsertDTO dto)
        {
            var WarehouseSetup = ObjectMapper.Map<WarehouseSetupInsertDTO, WarehouseSettings>(dto);
            await _repository.InsertAsync(WarehouseSetup);
            return 1;
        }

        /// <summary>
        /// 删除仓库
        /// </summary>
        public int DeleteWarehouseSetup(int id)
        {
            _repository.DeleteAsync(id);
            return 1;
        }

        /// <summary>
        /// 获取仓库列表
        /// </summary>
        public PagedResult GetWarehouseSetup(string? code, string? name, int page = 1, int limit = 2)
        {
            var predicate = PredicateBuilder.New<WarehouseSettings>(true);
            if (!string.IsNullOrEmpty(code))
            {
                predicate = predicate.And(m => m.WarehouseCode == code);
            }
            if (!string.IsNullOrEmpty(name))
            {
                predicate = predicate.And(m => m.WarehouseName == name);
            }
            var dto = _repository.GetListAsync(predicate).Result;
            PagedResult result = new PagedResult();
            result.PageCount = (int)Math.Ceiling((decimal)(dto.Count == 0 ? 1 : dto.Count) / limit);
            result.PageSize = limit;
            result.CurrentPage = page;
            result.RowCount = dto.Count;
            result.Queryable = dto.Skip((page - 1) * limit).Take(limit).AsQueryable();
            return result;
        }

        /// <summary>
        /// 根据ID获取仓库信息
        /// </summary>
        public  Task<WarehouseSettings> GetWarehouseSetupById(int id)
        {
            var model =  _repository.FirstOrDefaultAsync(x => x.Id == id);
            return model;
        }

        /// <summary>
        /// 更新仓库信息
        /// </summary>
        public async Task<int> UpdateWarehouseSetup(WarehouseSetupUpdateDTO dto)
        {
            var model = ObjectMapper.Map<WarehouseSetupUpdateDTO, WarehouseSettings>(dto);
            await _repository.UpdateAsync(model);
            return 1;
        }
    }

    
}
